package com.docmgmt.mvp.controller;

import com.docmgmt.mvp.dto.*;
import com.docmgmt.mvp.exception.UnauthorizedException;
import com.docmgmt.mvp.service.FileShareService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 文件分享 API（v3.0）
 * </p>
 *
 * @author Dora
 */
@Slf4j
@RestController
@RequestMapping("/api/v1")
@RequiredArgsConstructor
public class FileShareController {

    private final FileShareService fileShareService;

    /**
     * 5.2.1 创建分享链接
     *
     * POST /api/v1/files/{fileId}/share
     */
    @PostMapping("/files/{fileId}/share")
    public Result<FileShareVO> createShare(
            @PathVariable Long fileId,
            @RequestBody CreateShareRequest request) {

        Long userId = getCurrentUserId();

        log.info("POST /api/v1/files/{}/share - userId={}, request={}", fileId, userId, request);

        FileShareVO share = fileShareService.createShare(fileId, request, userId);

        return Result.success("分享创建成功", share);
    }

    /**
     * 5.2.2 访问分享链接
     *
     * GET /api/v1/share/{shareCode}
     */
    @GetMapping("/share/{shareCode}")
    public Result<AccessShareResponse> accessShare(
            @PathVariable String shareCode,
            @RequestParam(required = false) String password) {

        log.info("GET /api/v1/share/{} - password={}", shareCode, password != null ? "***" : "null");

        AccessShareResponse response = fileShareService.accessShare(shareCode, password);

        return Result.success("访问成功", response);
    }

    /**
     * 5.2.3 取消分享
     *
     * DELETE /api/v1/files/{fileId}/share/{shareId}
     */
    @DeleteMapping("/files/{fileId}/share/{shareId}")
    public Result<Void> cancelShare(
            @PathVariable Long fileId,
            @PathVariable Long shareId) {

        Long userId = getCurrentUserId();

        log.info("DELETE /api/v1/files/{}/share/{} - userId={}", fileId, shareId, userId);

        fileShareService.cancelShare(fileId, shareId, userId);

        return Result.success("分享已取消");
    }

    /**
     * 5.2.4 查询我的分享
     *
     * GET /api/v1/shares/my
     */
    @GetMapping("/shares/my")
    public Result<PagedResult<FileShareVO>> listMyShares(
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "20") Integer pageSize) {

        Long userId = getCurrentUserId();

        log.info("GET /api/v1/shares/my - userId={}, page={}, pageSize={}", userId, page, pageSize);

        PagedResult<FileShareVO> result = fileShareService.listMyShares(userId, page, pageSize);

        return Result.success("查询成功", result);
    }

    /**
     * 获取当前登录用户ID
     */
    private Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new UnauthorizedException("未登录");
        }

        Object principal = authentication.getPrincipal();
        if (principal instanceof Long) {
            return (Long) principal;
        } else if (principal instanceof String) {
            try {
                return Long.parseLong((String) principal);
            } catch (NumberFormatException e) {
                throw new UnauthorizedException("无效的用户ID");
            }
        }

        throw new UnauthorizedException("无法获取用户ID");
    }
}
